package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.igas.bomp.facade.BompMchntManageService;
import cc.rengu.igas.bomp.facade.enums.BompImageFileOprTypeEnum;
import cc.rengu.igas.bomp.facade.request.ImageFileUpDownloadRequest;
import cc.rengu.igas.bomp.facade.request.InstMchntRegisterRequest;
import cc.rengu.igas.bomp.facade.response.ImageFileUpDownloadResponse;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * @author 刘玉亮.LL
 */
@Slf4j
@Api(tags = "商户管理:平台商户管理")
@RestController
@RequestMapping(value = "/admin/merParam/platMchntInfo")
public class BPlatMchntInfoController extends BaseController {
    private long oprMenuId = 20000021;
    private String oprMenuName = "商户管理:平台商户管理";
    private long chkMenuId = 20000021;
    private String chkMenuName = "商户管理:平台商户管理";
    private String webNextUrl = "/admin/merParam/platMchntInfo/edit";
    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    private BompMchntManageService bompMchntManageService;

    @Autowired
    private IUpmpBPlatMchntInfoService platMchntInfoService;

    @Autowired
    private IUpmpOrganizationService organizationService;

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Autowired
    private IProfitConfInfoService profitConfInfoService;

    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;

    @Autowired
    private IWechatMchntInfoService bWechatMchntInfoService;


    //@RequiresPermissions("商户管理:平台商户管理")
    @GetMapping(value = "/list")
    public Map<String, Object> findByPage(QueryRequest request, UpmpBPlatMchntInfo entity) {
        return getDataTable(this.platMchntInfoService.findByPage(request, entity));
    }

    //@RequiresPermissions("商户管理:平台商户管理")
    @GetMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public Map<String, Object> editShow(@ModelAttribute("platMchntInfo") UpmpBPlatMchntInfo entity, Model model, HttpServletRequest request) throws RedpException {
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        LinkedHashMap<String, String> isMap = new LinkedHashMap<String, String>();
        isMap.put("1", "是");
        isMap.put("0", "否");
        String optFlag = request.getParameter("optFlag") == null ? "" : request.getParameter("optFlag");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        // 增加
        if ("add".equals(optFlag)) {
            String instId = request.getParameter("instId") == null ? "" : request.getParameter("instId");
            String crtOrgId = "";
            if (user.isAdmin()) {
                if (StringUtils.isEmpty(instId)) {
                    log.error("运营中心管理员新增数据必须先选择法人行！");
                    throw new RedpException("运营中心管理员新增数据必须先选择法人行！");
                } else {
                    UpmpOrganization headOrg = organizationService.getHeadOrgByCode(instId);
                    crtOrgId = (headOrg == null ? user.getOrgCode() : headOrg.getOrgCode());
                }
            } else {
                instId = (instId == null ? user.getInstId() : instId);
                crtOrgId = user.getOrgCode();
            }
            UpmpOrganization org = organizationService.getOrgByCode(crtOrgId, instId);

            entity.setId("0");
            entity.setPlatMchntNo("00000000");
            entity.setIsProfitFlag("0");
            entity.setAuditStatus(BusinessContainer.status_01);
            entity.setPlatMchntStatus(BusinessContainer.agentStatus_00);
            entity.setManageInstId(org.getOrgCode());
            entity.setInstId(org.getInstId());
            result.put("crtOrgName", org.getOrgName());
            result.put("profitConfInfoList", "[]");
            result.put("manageInstName", org.getOrgName());
        }
        // 修改，注销，停用，启用，详情，审批
        List<ProfitConfInfo> selectedProfitConfInfoList = new ArrayList<>();
        if ("upd".equals(optFlag) || "cancel".equals(optFlag) || "stop".equals(optFlag) ||
                "use".equals(optFlag) || "detail".equals(optFlag) || "chk".equals(optFlag)) {
            String id = request.getParameter("id") == null ? "" : request.getParameter("id");
            if (!"".equals(id)) {
                if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag) || PageOptFlagEnum.OPT_FLAG_CHECK_VIEW.getType().equals(optFlag)) {
                    BizTmp tmp = bizTmpService.getById(id);
                    if (Common.isBlank(tmp)) {
                        log.error("根据id没有找到指定临时表数据！");
                        throw new RedpException("根据id没有找到指定临时表数据！");
                    }
                    String bizdata = "";
                    if (null != tmp.getBizData1()) {
                        bizdata += tmp.getBizData1();
                    }
                    if (null != tmp.getBizData2()) {
                        bizdata += tmp.getBizData2();
                    }
                    if (null != tmp.getBizData3()) {
                        bizdata += tmp.getBizData3();
                    }
                    entity = JSON.parseObject(bizdata, UpmpBPlatMchntInfo.class);
                    // 加载分润配置信息
                    if ("1".equals(entity.getIsProfitFlag())) {
                        selectedProfitConfInfoList = bizTmpService.getBizTmpByInstIdAndMasterKeyAndEname(entity.getInstId(), ProfitConfInfo.class, entity.getId());
                    }
                    result.put("profitConfInfoList", JSON.toJSONString(selectedProfitConfInfoList));
                    // 加载微信商户信息
                    List<WechatMchntInfo> bWechatMchntInfoList = bizTmpService.getBizTmpByInstIdAndMasterKeyAndEname(entity.getInstId(), WechatMchntInfo.class, entity.getId());
                    if (null != bWechatMchntInfoList && bWechatMchntInfoList.size() > 0) {
                        // 配置需要向微信进件
                        WechatMchntInfo bWechatMchntInfo = bWechatMchntInfoList.get(0);
                        entity.setIsWechatEntryFlag("1");
                        entity.setChannelType(bWechatMchntInfo.getDstChannelType());
                        entity.setAppId(bWechatMchntInfo.getAppId());
                        entity.setAppSecretKey(bWechatMchntInfo.getAppSecretKey());
                        entity.setMiniAppId(bWechatMchntInfo.getMiniAppId());
                        entity.setMiniSecretKey(bWechatMchntInfo.getMiniSecretKey());
                    }
                    // 处理修改前后数据
                    String auditStatus = tmp.getAuditStatus();
                    if (BusinessContainer.status_41.equals(auditStatus)) {
                        UpmpBPlatMchntInfo oldEntity = platMchntInfoService.getById(id);
                        UpmpBPlatMchntInfo changeData = compEntity(entity, oldEntity);
                        //修改时对比详情数据
                        result.put("checkUpdate", "Y");
                        result.put("changeData", StringEscapeUtils.escapeHtml4(JSON.toJSONString(changeData, SerializerFeature.WriteMapNullValue)));
                    }
                    if (PageOptFlagEnum.OPT_FLAG_CHECK_VIEW.getType().equals(optFlag)) {
                        optFlag = "details";
                    }
                } else {
                    entity = platMchntInfoService.getById(id);
                    //分润数据 固定金额类型的 如果存在多条将合并显示
                    String settleType = entity.getSettleType();
                    if ("TN".equals(settleType)) {
                        entity.setSettleCycleType("1");
                    } else if ("MT".equals(settleType)) {
                        entity.setSettleCycleType("2");
                    } else if ("ST".equals(settleType)) {
                        entity.setSettleCycleType("3");
                    }
                    // 加载分润配置信息
                    selectedProfitConfInfoList = profitConfInfoService.findByBizCode(entity.getPlatMchntNo());
                    result.put("profitConfInfoList", JSON.toJSONString(selectedProfitConfInfoList));
                    // 加载微信商户信息
                    WechatMchntInfo bWechatMchntInfo = bWechatMchntInfoService.getBWechatMchntInfoByMchntNo(entity.getPlatMchntNo(),entity.getInstId());
                    if (null != bWechatMchntInfo) {
                        // 配置需要向微信进件
                        entity.setIsWechatEntryFlag("1");
                        entity.setChannelType(bWechatMchntInfo.getDstChannelType());
                        entity.setAppId(bWechatMchntInfo.getAppId());
                        entity.setAppSecretKey(bWechatMchntInfo.getAppSecretKey());
                        entity.setMiniAppId(bWechatMchntInfo.getMiniAppId());
                        entity.setMiniSecretKey(bWechatMchntInfo.getMiniSecretKey());
                    }
                }
                UpmpOrganization organization = organizationService.getOrgByCode(entity.getCrtOrgId(), entity.getInstId());
                if (null == organization) {
                    organization = organizationService.getOrgByCode(entity.getCrtOrgId(), user.getInstId());
                }
                UpmpOrganization manageOrg = organizationService.getOrgByCode(entity.getManageInstId(), entity.getInstId());
                if (null == manageOrg) {
                    manageOrg = organizationService.getOrgByCode(entity.getManageInstId(), user.getInstId());
                }
                result.put("crtOrgName", null == organization ? "" : organization.getOrgName());
                result.put("manageInstName", null == manageOrg ? "" : manageOrg.getOrgName());
            } else {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常！");
            }
        }

        // 1、生成所有基础产品的分润配置
        Map<BBaseProdInfo, List<ProfitConfInfo>> bBaseProdProfitConfListMap = platMchntInfoService.getProfitConfInfoList();
        // 将所有的产品分润配置，赋值已配置的分润配置id。用于前端反显
        Map<String, String> selectProfitConfInfoIdMap = new HashMap<>();
        for (ProfitConfInfo profitConfInfo : selectedProfitConfInfoList) {
            String sb = profitConfInfo.getBizProdCode() +
                    profitConfInfo.getSubProdType() +
                    (StringUtils.isNotBlank(profitConfInfo.getDstChannelType()) ? profitConfInfo.getDstChannelType() : "");
            //
            selectProfitConfInfoIdMap.put(sb, profitConfInfo.getId());
        }
        for (BBaseProdInfo bBaseProdInfo : bBaseProdProfitConfListMap.keySet()) {
            List<ProfitConfInfo> profitConfInfos = bBaseProdProfitConfListMap.get(bBaseProdInfo);
            for (ProfitConfInfo profitConfInfo : profitConfInfos) {
                String sb = profitConfInfo.getBizProdCode() +
                        profitConfInfo.getSubProdType() +
                        (StringUtils.isNotBlank(profitConfInfo.getDstChannelType()) ? profitConfInfo.getDstChannelType() : "");
                if (selectProfitConfInfoIdMap.containsKey(sb)) {
                    // 替换id
                    profitConfInfo.setId(selectProfitConfInfoIdMap.get(sb));
                }
            }
        }
        //
        List<BBaseProdInfo> bBaseProdInfos = new ArrayList<>(bBaseProdProfitConfListMap.keySet());
        result.put("baseProdInfoList", JSON.toJSONString(bBaseProdInfos));

        List<ProfitConfInfo> profitConfInfos = new ArrayList<>();
        for (List<ProfitConfInfo> pc : bBaseProdProfitConfListMap.values()) {
            profitConfInfos.addAll(pc);
        }
        result.put("profitConfInfoAll", JSON.toJSONString(profitConfInfos));

        //
        result.put("optFlag", optFlag);
        result.put("entity", entity);
        result.put("isMap", isMap);
        //
        result.put("manageInstId", entity.getManageInstId());
        result.put("auditStatus", entity.getAuditStatus());
        result.put("platMchntNo", entity.getPlatMchntNo());
        result.put("crtOrgId", entity.getCrtOrgId());
        result.put("oprId", entity.getOprId());
        result.put("createTime", entity.getCreateTime());
        result.put("lastOprId", entity.getLastOprId());
        result.put("lastUpdateTime", entity.getLastUpdateTime());
        result.put("instId", entity.getInstId());
        return result;
    }

    private UpmpBPlatMchntInfo compEntity(UpmpBPlatMchntInfo entity, UpmpBPlatMchntInfo oldEntity) throws RedpException {
        UpmpBPlatMchntInfo changeData = new UpmpBPlatMchntInfo();
        if (Common.isBlank(entity) || Common.isBlank(oldEntity)) {
            throw new RedpException("详情数据异常");
        }

        if (!(StringUtils.equals(entity.getPlatMchntName(), oldEntity.getPlatMchntName()))) {
            changeData.setPlatMchntName(oldEntity.getPlatMchntName());
        } else {
            changeData.setPlatMchntName("unChange--data");//提示前端数据未改变
        }

        //
        if (!(StringUtils.equals(entity.getId(), oldEntity.getId()))) {
            changeData.setId(oldEntity.getId());
        } else {
            changeData.setId("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getLicenceType(), oldEntity.getLicenceType()))) {
            changeData.setLicenceType(oldEntity.getLicenceType());
        } else {
            changeData.setLicenceType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getLicenceCode(), oldEntity.getLicenceCode()))) {
            changeData.setLicenceCode(oldEntity.getLicenceCode());
        } else {
            changeData.setLicenceCode("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getArtifName(), oldEntity.getArtifName()))) {
            changeData.setArtifName(oldEntity.getArtifName());
        } else {
            changeData.setArtifName("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getArtifCertType(), oldEntity.getArtifCertType()))) {
            changeData.setArtifCertType(oldEntity.getArtifCertType());
        } else {
            changeData.setArtifCertType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getArtifCertNo(), oldEntity.getArtifCertNo()))) {
            changeData.setArtifCertNo(oldEntity.getArtifCertNo());
        } else {
            changeData.setArtifCertNo("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getArtifMobile(), oldEntity.getArtifMobile()))) {
            changeData.setArtifMobile(oldEntity.getArtifMobile());
        } else {
            changeData.setArtifMobile("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getArtifEmail(), oldEntity.getArtifEmail()))) {
            changeData.setArtifEmail(oldEntity.getArtifEmail());
        } else {
            changeData.setArtifEmail("unChange--data");//提示前端数据未改变
        }
        //
        if (!(StringUtils.equals(entity.getContactName(), oldEntity.getContactName()))) {
            changeData.setContactName(oldEntity.getContactName());
        } else {
            changeData.setContactName("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getContactPhone(), oldEntity.getContactPhone()))) {
            changeData.setContactPhone(oldEntity.getContactPhone());
        } else {
            changeData.setContactPhone("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getContactEmaiil(), oldEntity.getContactEmaiil()))) {
            changeData.setContactEmaiil(oldEntity.getContactEmaiil());
        } else {
            changeData.setContactEmaiil("unChange--data");//提示前端数据未改变
        }

        if (!(StringUtils.equals(entity.getMchntNetworkDomain(), oldEntity.getMchntNetworkDomain()))) {
            changeData.setMchntNetworkDomain(oldEntity.getMchntNetworkDomain());
        } else {
            changeData.setMchntNetworkDomain("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getIcpRecordNo(), oldEntity.getIcpRecordNo()))) {
            changeData.setIcpRecordNo(oldEntity.getIcpRecordNo());
        } else {
            changeData.setIcpRecordNo("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getIp(), oldEntity.getIp()))) {
            changeData.setIp(oldEntity.getIp());
        } else {
            changeData.setIp("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getSignType(), oldEntity.getSignType()))) {
            changeData.setSignType(oldEntity.getSignType());
        } else {
            changeData.setSignType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getIsProfitFlag(), oldEntity.getIsProfitFlag()))) {
            changeData.setIsProfitFlag(oldEntity.getIsProfitFlag());
        } else {
            changeData.setIsProfitFlag("unChange--data");//提示前端数据未改变
        }

        if (!(StringUtils.equals(entity.getSettleType(), oldEntity.getSettleType()))) {
            changeData.setSettleType(oldEntity.getSettleType());
        } else {
            changeData.setSettleType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getSettleType(), oldEntity.getSettleType())) || !(StringUtils.equals(entity.getSettleCycle() + "", oldEntity.getSettleCycle() + ""))) {
            changeData.setSettleType(oldEntity.getSettleType());
            changeData.setSettleCycle(oldEntity.getSettleCycle());
        } else {
            changeData.setSettleType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getSettleAcctType(), oldEntity.getSettleAcctType()))) {
            changeData.setSettleAcctType(oldEntity.getSettleAcctType());
        } else {
            changeData.setSettleAcctType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getSettleAcctNo(), oldEntity.getSettleAcctNo()))) {
            changeData.setSettleAcctNo(oldEntity.getSettleAcctNo());
        } else {
            changeData.setSettleAcctNo("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getSettleAcctName(), oldEntity.getSettleAcctName()))) {
            changeData.setSettleAcctName(oldEntity.getSettleAcctName());
        } else {
            changeData.setSettleAcctName("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getAcctOpenBankNo(), oldEntity.getAcctOpenBankNo()))) {
            changeData.setAcctOpenBankNo(oldEntity.getAcctOpenBankNo());
        } else {
            changeData.setAcctOpenBankNo("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getAcctOpenBankName(), oldEntity.getAcctOpenBankName()))) {
            changeData.setAcctOpenBankName(oldEntity.getAcctOpenBankName());
        } else {
            changeData.setAcctOpenBankName("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getEnterRegisterType(), oldEntity.getEnterRegisterType()))) {
            changeData.setEnterRegisterType(oldEntity.getEnterRegisterType());
        } else {
            changeData.setEnterRegisterType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getManagementScope(), oldEntity.getManagementScope()))) {
            changeData.setManagementScope(oldEntity.getManagementScope());
        } else {
            changeData.setManagementScope("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getIndustryType(), oldEntity.getIndustryType()))) {
            changeData.setIndustryType(oldEntity.getIndustryType());
        } else {
            changeData.setIndustryType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getCashDeskName(), oldEntity.getCashDeskName()))) {
            changeData.setCashDeskName(oldEntity.getCashDeskName());
        } else {
            changeData.setCashDeskName("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getLogoPath(), oldEntity.getLogoPath()))) {
            changeData.setLogoPath(oldEntity.getLogoPath());
        } else {
            changeData.setLogoPath("unChange--data");//提示前端数据未改变
        }

        if (!(StringUtils.equals(entity.getGrantCreditFlag(), oldEntity.getGrantCreditFlag()))) {
            changeData.setGrantCreditFlag(oldEntity.getGrantCreditFlag());
        } else {
            changeData.setGrantCreditFlag("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getGuaranteeFlag(), oldEntity.getGuaranteeFlag()))) {
            changeData.setGuaranteeFlag(oldEntity.getGuaranteeFlag());
        } else {
            changeData.setGuaranteeFlag("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getIsWechatEntryFlag(), oldEntity.getIsWechatEntryFlag()))) {
            changeData.setIsWechatEntryFlag(oldEntity.getIsWechatEntryFlag());
        } else {
            changeData.setIsWechatEntryFlag("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getChannelType(), oldEntity.getChannelType()))) {
            changeData.setChannelType(oldEntity.getChannelType());
        } else {
            changeData.setChannelType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getAppId(), oldEntity.getAppId()))) {
            changeData.setAppId(oldEntity.getAppId());
        } else {
            changeData.setAppId("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getAppSecretKey(), oldEntity.getAppSecretKey()))) {
            changeData.setAppSecretKey(oldEntity.getAppSecretKey());
        } else {
            changeData.setAppSecretKey("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getMiniAppId(), oldEntity.getMiniAppId()))) {
            changeData.setMiniAppId(oldEntity.getMiniAppId());
        } else {
            changeData.setMiniAppId("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getMiniSecretKey(), oldEntity.getMiniSecretKey()))) {
            changeData.setMiniSecretKey(oldEntity.getMiniSecretKey());
        } else {
            changeData.setMiniSecretKey("unChange--data");//提示前端数据未改变
        }

        return changeData;
    }


    //@RequiresPermissions("商户管理:平台商户管理")
    @PostMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public OperationResult editSave(@ModelAttribute("platMchntInfo") UpmpBPlatMchntInfo entity, Model model, HttpServletRequest request) throws RedpException {
        String optFlag = request.getParameter("optFlag") == null ? "" : request.getParameter("optFlag");
        if (entity.getProfitConfInfoList() != null && !entity.getProfitConfInfoList().equals("")) {
            entity.setProfitConfInfoList(entity.getProfitConfInfoList().replaceAll("&quot;", "\""));
        }
        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
        } else {
            menuId = String.valueOf(oprMenuId);
        }
        return platMchntInfoService.saveData(menuId, oprMenuName, entity, request, webNextUrl);
    }

    /**
     * 审批
     *
     * @param entity
     * @param model
     * @param request
     * @return
     */


    //@RequiresPermissions("商户管理:平台商户管理")
    @PostMapping(value = "/editPass")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String")
    })
    public OperationResult editpass(@ModelAttribute("platMchntInfo") UpmpBPlatMchntInfo entity, Model model, HttpServletRequest request) throws RedpException {
        if (entity.getProfitConfInfoList() != null && !entity.getProfitConfInfoList().equals("")) {
            entity.setProfitConfInfoList(entity.getProfitConfInfoList().replaceAll("&quot;", "\""));
        }
        String id = request.getParameter("id");
        String optFlag = request.getParameter("optFlag");
        String auditRefuseReason = entity.getAuditRefuseReason();
        String cancelReason = entity.getCancelReason();
        String stopReason = entity.getStopReason();
        entity = platMchntInfoService.getById(id);
        entity.setAuditRefuseReason(auditRefuseReason);
        entity.setCancelReason(cancelReason);
        entity.setStopReason(stopReason);

        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
        } else {
            menuId = String.valueOf(oprMenuId);
        }
        return platMchntInfoService.chkData(menuId, oprMenuName, entity, request, webNextUrl);
    }


    //@RequiresPermissions("商户管理:平台商户管理")
    @PostMapping(value = "/thirdEntry")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "mchntNo", value = "商户号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "channelType", value = "实名认证申请单号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "oprType", value = "01新增|02修改|03审核", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "appId", value = "实名认证申请单号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "miniAppId", value = "商户号", required = true, dataType = "String")
    })
    public OperationResult thirdEntry(HttpServletRequest request) throws RedpException {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String mchntNo = request.getParameter("mchntNo");
        String channelType = request.getParameter("channelType");
        String appId = request.getParameter("appId");
        String miniAppId = request.getParameter("miniAppId");
        String oprType = request.getParameter("oprType");
        String instId = request.getParameter("instId");
        InstMchntRegisterRequest req = new InstMchntRegisterRequest();
        req.setMchntNo(mchntNo);
        req.setChannelType(channelType);
        req.setChannelFlag("01");
        req.setWechatAppid(appId);
        req.setWechatMiniAppid(miniAppId);
        req.setUserId(user.getId());
        req.setMchntBizFlag("01");
        req.setOprType(oprType);
        return bMchntBaseInfoService.thirdEntry(instId, req, bMchntBaseInfoService.genMerOrder(user.getInstId()));
    }

    @DeleteMapping("/{ids}")
    public void delete(@PathVariable String ids) throws RedpException {
        String[] idsArr = ids.split(StringPool.COMMA);
        for (String s : idsArr) {
            UpmpBPlatMchntInfo entity = platMchntInfoService.getById(s);
            java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
            String status = entity.getPlatMchntNo();
            if (!BusinessContainer.status_03.equals(status)) {
                throw new RedpException("非新增审批拒绝的集团商户，不能进行删除");
            }
        }
        this.platMchntInfoService.getBaseMapper().deleteBatchIds(Arrays.asList(idsArr));
    }
    /**
     * 查询省、市、县区
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/provinceSelect2List")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "q", value = "参数", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String")
    })
    public Map<String, Object> provinceSelect2List(HttpServletRequest request, @NotBlank(message = "{required}") String instId) {
        String q = request.getParameter("q");
        if (null == q) {
            return null;
        }
        q = q.replaceAll("&amp;", "&");
        String[] param = q.split("&");
        if (param.length > 1) {
            return CommonUtils.dataDictToSelect2(upmpSysParamService, param[1], instId);
        } else {
            return CommonUtils.dataDictToSelect2(upmpSysParamService, param[0], instId);
        }
    }
}
